import redis from 'ioredis'
import elementUI from 'element-ui'

export default{
  createConnection(item){
    //集群模式
    if(item.type==='Cluster'){
      return this.createClusterConnection(item)
    }
    //单机模式
    return this.createStandAloneConnection(item)
  },
  //单机连接模式
  createStandAloneConnection (item) {
    const options = {
      host:item.host,
      port:parseInt(item.port), 
      connectTimeout: 1000,
      retryStrategy: (options) => { return this.retryStragety(options)},
      password: item.password,
      showFriendlyErrorStack:true
    }
    const _redis=new redis(options);
    _redis.on('error',(err)=>{
      this.exceptionHandler(err)
    })
    return _redis;
  },
  //Cluster集群模式连接
  createClusterConnection(item){
    var clusters=this.generateNode(item);
    const options = {
      connectTimeout: 1000,
      password: item.password
    }
    const cluster=new redis.Cluster(clusters,
      {
        clusterRetryStrategy:(options) => { return this.retryStragety(options)},
        redisOptions:options,
        showFriendlyErrorStack:true
      }
    )
    //错误处理
    cluster.on("error",(err)=>{
      this.exceptionHandler(err)
    })
    return cluster;
  },
  //重试机制
  retryStragety (options) {
    return false;
  },
  generateNode(item){
    var node =[];
      node.push({"host":item.host,"port":parseInt(item.port)})
    return node;
  },
  exceptionHandler(err){
    //密码错误
    if(err.message==="ERR invalid password"){
      elementUI.Message({
        type: 'error',
        message: window.$Vue.$t('RedisOperating.passWordError')
      })
    //连接超时
    }else if(err.message==="connect ETIMEDOUT"){
      elementUI.Message({
        type: 'error',
        message: window.$Vue.$t('RedisOperating.connectionError')
      })
    //其他异常处理
    }else if(err.message==="NOAUTH Authentication required."){
      elementUI.Message({
        type: 'error',
        message: window.$Vue.$t('RedisOperating.NeedPwd')
      })
    //集群连接失败无法刷新
    }else if(err.message==="Failed to refresh slots cache."){
      elementUI.Message({
        type: 'error',
        message: window.$Vue.$t('RedisOperating.FailedRefreshSlots')
      })
    }else{
      elementUI.Message({
        type: 'error',
        message: err.message
      })
    }
    return false;
  }
}
